// pages/coupon/buycoupon/index.js
import {
  getCouponById
} from '../../../sers/coupon/coupon';
import {
  getCouponByCode,
  getCouponByCodeNow
} from '../../../sers/coupon/coupon';
var wxbarcode = require('../../../utils/index');
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    myCoupon: null,
    txm: '../../../images/txm.png',
    erwm: '../../../images/erwm.png',
    strFontSize: '30rpx',
    tittop: app.globalData.tittop + 'rpx',
    lbtop: app.globalData.lbtop + 'rpx',
    isWindows: app.globalData.isWindows,
    remark: '',
    isExpanded: false,
    showExpandBtn: true,
    orderId: '',
    balanceNow: '',
    mobileNow: "",
    refreshTimer: null,
  },

  toggleText() {
    this.setData({
      isExpanded: !this.data.isExpanded,
      showExpandBtn: true
    });
  },
  checkTextOverflow() {
    const query = this.createSelectorQuery();
    query.select('.text-ellipsis').boundingClientRect(res => {
      if (res && res.height > 0) {
        // 估算 5 行高度（假设每行约 40rpx）
        const lineHeight = 40;
        const maxHeight = lineHeight * 5;
        // 判断是否超过 5 行
        if (res.height > maxHeight) {
          this.setData({
            showExpandBtn: true
          });
        }
      }
    }).exec();
  },
  //分享自定义
  share_btn(e) {
    let cardNo = this.data.myCoupon.card_no
    wx.navigateTo({
      url: '/pages/coupon/sharedetail/index?couponId=' + cardNo
    });
  },
  // 定义分享内容
  onShareAppMessage() {
    return {
      title: this.data.coupon.couponName,
      path: '/pages/coupon/buycoupon/index?couponId=' + this.data.coupon.couponId,
      imageUrl: '',
      success: function (res) {
        console.log('分享成功', res);
        wx.showToast({
          title: '分享成功'
        });
      },
      fail: function (res) {
        console.log('分享失败', res);
        wx.showToast({
          title: '分享取消或失败'
        });
      }
    };
  },
  /**
   * 生命周期函数--监听页面加载
   */

  onLoad(options) {
    wx.setStorageSync('lastUpdate', Date.now());
    this.orderId = options.couponCode
    this.getData(); // 获取初始数据
    this.startAutoRefresh(3000); // 每3秒自动调用 getNow()
  },
  getData() {
    getCouponByCode(this.orderId).then(coupon => {
      var couponDetail = coupon.data
      if (couponDetail[0] !== null) {
        if (couponDetail[0].card_name.length > 40 || couponDetail[0].desc.length > 40) {
          this.setData({
            strFontSize: '24rpx'
          });
        }
      }
      var temp = couponDetail[0].desc;
      var temp1 = temp.replace(/\\n/g, '\n');
      this.setData({
        remark: temp1
      });
      this.setData({
        myCoupon: couponDetail[0]
      });
      console.log(this.data.myCoupon)
      const balance = this.data.myCoupon.balance
      this.setData({
        'myCoupon.balance': Math.trunc(balance)
      })
      wxbarcode.barcode('barcode', this.data.myCoupon.card_no, 680, 200);
      wxbarcode.qrcode('qrcode', this.data.myCoupon.card_no, 420, 420);
      this.balanceNow = Math.trunc(balance)
      app.globalData.balance = balance;
      // this.getNow()
    }).catch(error => {
      console.log(error);
    });
  },
  getNow() {
    var user = wx.getStorageSync("cache_shop_user_info_key") || null;
    var mobile;
    if (user != null) {
      mobile = user.mobile
    } else {
      if (app.globalData.userInfo != null) {
        mobile = app.globalData.userInfo.mobile
      }
    }
    let parame = {
      mobile: mobile,
      cardNo: this.orderId,
      balance: app.globalData.balance
    }
    this.timeoutId = null;
    wx.request({
      url: app.get_request_url("CouponDetailRefresh", "coupons"),
      method: "POST",
      data: parame,
      dataType: "json",
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: (res) => {
        if (res.data.code == 0) {
          this.setData({
            myCoupon: res.data.data
          });
          app.globalData.balance = res.data.data.balance
          this.getData();
          // 设置一个3秒的延迟
          setTimeout(() => {
            wx.showToast({
              title: res.data.msg,
              duration: 3000,
            })
          }, 100);
        } else {}
      },
      fail: () => {
        app.showToast("服务器请求出错");
      }
    });
  },
  // 启动自动刷新
  startAutoRefresh(interval = 5000) {
    // 先清除可能存在的旧定时器
    if (this.refreshTimer) {
      clearInterval(this.refreshTimer);
      // this.refreshTimer = null;
    }
    // 设置新的定时器
    this.refreshTimer = setInterval(() => {
      console.log('定时刷新触发');
      this.getNow()
    }, interval);
  },
  // 停止定时器
  stopTimer() {
    if (this.refreshTimer) {
      clearInterval(this.refreshTimer);
      this.refreshTimer = null; // 清除引用，帮助垃圾回收
      console.log('定时器已停止');
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},
  /**
   * 生命周期函数--监听页面显示
   */
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    this.stopTimer();
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    this.stopTimer();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.onLoad();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  toBack(e) {
    wx.navigateBack({
      delta: 1
    });
  },

  refundCoupon(e) {
    console.log("ad")
    var user = wx.getStorageSync("cache_shop_user_info_key") || null;
    var mobile;
    if (user != null) {
      mobile = user.mobile
    } else {
      if (app.globalData.userInfo != null) {
        mobile = app.globalData.userInfo.mobile
      }
    }
    this.mobileNow = mobile
    var couponNo = this.data.myCoupon.card_no;
    var orderNo = this.data.myCoupon.order_no
    wx.showModal({
      title: '提示',
      content: '确认退券',
      success: function (res) {
        if (res.confirm) {
          wx.showLoading({
            title: '加载中...',
            mask: true,
          });
          wx.request({
            url: app.get_request_url("RefundCoupon", "coupons"),
            method: "POST",
            data: {
              couponCode: couponNo,
              mobile: mobile,
              orderNo: orderNo,
            },
            dataType: "json",
            success: res => {
              wx.hideLoading();
              if (res.data.code == 0) {
                app.showToast("退券成功,金额将原路返回,请稍后查看.");
                setTimeout(function () {
                  wx.navigateBack({
                    success: res => {
                      wx.reLaunch({
                        url: '/pages/coupon/index?index=1'
                      })
                    }
                  });
                }, 2000);
              } else {
                app.showToast(res.data.msg);
              }
            },
            fail: () => {
              wx.hideLoading();
              wx.stopPullDownRefresh();
              app.showToast("服务器请求出错");
            }
          });
        }
      }
    });
  },
})